import React, { useEffect, useState, useRef, useMemo } from 'react';
import { NavigationProp, RouteProp, StackActions } from '@react-navigation/native';
import { useReactive } from 'ahooks';
import { StyleSheet, TouchableOpacity, View, Text, Image, TextInput } from 'react-native';
import { CommonStyle } from '../../../common/commonStyle.ts';
import { useSelector } from 'react-redux';
import { AppDispatch, RootState } from '../../../redux/store.ts';
import { Container, TextArea, ScrollView, Modal, Button, AlertDialog } from 'native-base';
import { Loading } from '../../../component/LoadingOverlay.tsx';
import { useToast } from 'react-native-toast-notifications';
import to from '../../../utils/to.ts';
import AntDesign from 'react-native-vector-icons/AntDesign';
import Footer from '../../../component/Footer.tsx';
import UploadMedia from '../../../component/UploadMedia.tsx';
import CascadingPicker, { TreeNode } from '../../../component/PickerCascader.tsx';
import UserRequest from '../../../request/userRequest.ts';
import HomeRequest from '../../../request/homeRequest.ts';
import Tools from '../../../utils/Tools.ts';
import Cell from '../../../component/Cell.tsx';
import Stepper from '../../../component/Stepper.tsx';

interface ITrappedReportProps {
  navigation: NavigationProp<any, 'trappedReport'>;
  route: RouteProp<{ trappedReport: any }, 'trappedReport'>;
}

interface IData {
  pickerBuildShow: boolean;
  cascader: TreeNode[]; // 选中的楼栋层数据
  cascaderData: TreeNode[]; // 楼栋层数据
  selectedBuildIds: number[]; // 选中的楼栋层ids
  residentAddress: any;
  params: any;
  address: string;
  trapDesc: string;
  video: string;
  alarmRecord: IGetAlarmRecord[];
  selectId: number;
  trapNum: number;
  historyList: ITrappedList[];
}

const TrappedReport: React.FC<ITrappedReportProps> = ({ navigation, route }) => {
  const data = useReactive<IData>({
    pickerBuildShow: false,
    cascader: [],
    cascaderData: [],
    selectedBuildIds: [],
    residentAddress: {
      name: '',
    },
    params: {},
    address: '',
    trapDesc: '',
    video: '',
    alarmRecord: [],
    selectId: 0,
    trapNum: 1,
    historyList: [],
  });

  const list = [
    {
      name: '所在楼层',
      type: 1,
    },
    {
      name: '详细位置',
      type: 2,
    },
    {
      name: '灾情描述',
      type: 3,
    },
    {
      name: '上传视频',
      type: 4,
    },
  ];

  const beeperId = useSelector((state: RootState) => state.beeperId);

  const [showModal, setShowModal] = useState(false);

  const [showRecordModal, setShowRecordModal] = useState(false);

  const [showTipsModal, setShowTipsModal] = useState(false);

  const toast = useToast();

  /**
   * 获取该小区楼栋层
   * @param villageId
   */
  const fetchBuildingTree = (beeperId: number) => {
    UserRequest.BuildingTree({ beeperId })
      .then((res) => {
        data.cascaderData = res.data;
      })
      .catch((err) => {});
  };

  const getStepperNum = (num: number) => {
    data.trapNum = num;
  };

  const getVideoUri = (uri: string) => {
    data.video = uri;
  };

  const setTextAreaValue = (text: string, type: number) => {
    if (type === 2) {
      data.address = text;
    } else {
      data.trapDesc = text;
    }
  };

  const getLocation = (type: string) => {
    //Y清除 N不清除
    if (type === 'Y') {
      data.residentAddress.name = '';
      data.cascader = [];
      data.selectedBuildIds = [];
      data.params = {};
    }
    navigation.navigate('selectMapPoint');
  };

  // 获取消防报警记录
  const fetchAlarmRecord = () => {
    Loading.show('加载中');
    HomeRequest.GetAlarmRecord({ beeperId: beeperId })
      .then((res) => {
        Loading.hide();
        if (res.data.length > 0) {
          data.alarmRecord = res.data;
          setShowRecordModal(true);
        } else {
          setShowTipsModal(true);
        }
      })
      .catch((err) => {
        Loading.hide();
      });
  };

  // 获取历史上报记录
  const getHistoryTrappedRecord = () => {
    Loading.show('加载中');
    HomeRequest.GetHistoryTrapped({ alarmId: data.selectId })
      .then((res) => {
        Loading.hide();
        if (res.data.length > 0) {
          data.historyList = res.data;
          data.historyList = data.historyList.map((item) => {
            return {
              ...item,
              address: item.buildName + item.unitName + item.floorName + item.houseNumber,
            };
          });
        }
      })
      .catch((err) => {
        Loading.hide();
      });
  };

  //受困上报提交
  const TrappedSubmit = () => {
    const { params, residentAddress, address, trapDesc, video, selectId, trapNum } = data;
    Loading.show('正在提交中');
    let datas = {
      alarmId: selectId,
      trapDesc: trapDesc,
      trapVideos: video ? Tools.convertFileToBase64(video) : '',
      site: address,
      buildId: params.buildId,
      buildName: params.buildName,
      unitId: params.unitId,
      unitName: params.unitName,
      floorId: params.floorId,
      floorName: params.floorName,
      houseNumberId: params.houseNumberId,
      houseNumber: params.houseNumber,
      trapNum: trapNum,
    };
    HomeRequest.TrappedUpload(datas)
      .then((res) => {
        Loading.hide();
        if (res.data === null) {
          toast.show('提交成功', { placement: 'bottom' });
        }
      })
      .catch((err) => {
        Loading.hide();
      });
  };

  useEffect(() => {
    fetchBuildingTree(beeperId);
    fetchAlarmRecord();
  }, []);

  const stateShow = (name: string, type: number) => {
    if (type === 1) {
      return (
        <TouchableOpacity
          onPress={() => {
            data.pickerBuildShow = true;
          }}
        >
          <View style={styles.ldcView}>
            <Text>{data.residentAddress?.name ? data.residentAddress?.name : '请选择栋单元层'}</Text>
            <AntDesign
              onPress={(event) => {
                event.stopPropagation(); // 阻止事件冒泡
                data.residentAddress.name = '';
              }}
              name="closecircleo"
              size={16}
              color={'#ccc'}
            ></AntDesign>
          </View>
        </TouchableOpacity>
      );
    } else if (type === 2 || type === 3) {
      const phname = '请填写' + name;
      return (
        <View>
          <TextArea autoCompleteType="off" value={type === 2 ? data.address : data.trapDesc} h={20} placeholder={phname} w="100%" onChangeText={(text) => setTextAreaValue(text, type)} />
        </View>
      );
    } else if (type == 4) {
      return <UploadMedia mediaType={'video'} onChange={getVideoUri}></UploadMedia>;
    }
  };

  /**
   * 联动选择器选择
   * @param val
   * @param ids
   */
  const handleCascadingChange = (val: TreeNode[], ids: number[]) => {
    data.cascader = val;
    data.selectedBuildIds = ids;
    ['buildHouseNumberNames', 'buildId', 'unitId', 'floorId', 'houseNumberId', 'buildName', 'unitName', 'floorName', 'houseNumber'].forEach((item) => {
      delete data.params[item];
    });
    data.params.buildHouseNumberNames = '';
    data.cascader.forEach((item, index) => {
      data.params.buildHouseNumberNames += index === 0 ? `${item.name}` : ` ${item.name}`;
      if (item.levels === 1) data.params = { ...data.params, buildId: item.id, buildName: item.name };
      if (item.levels === 2) data.params = { ...data.params, unitId: item.id, unitName: item.name };
      if (item.levels === 3) data.params = { ...data.params, floorId: item.id, floorName: item.name };
      if (item.levels === 4) data.params = { ...data.params, houseNumberId: item.id, houseNumber: item.name };
    });
    data.residentAddress.name = data.params.buildName + '/' + data.params.unitName + '/' + data.params.floorName + '/' + data.params.houseNumber;
    data.pickerBuildShow = false;
  };

  const LeftChildView = () => {
    return (
      <View>
        <Text>受困人数</Text>
      </View>
    );
  };

  return (
    <ScrollView style={styles.container}>
      {data.historyList.length > 0 && <Footer title="历史上报"></Footer>}
      {data.historyList.length > 0 &&
        data.historyList.map((item, index) => (
          <View style={styles.fireInfo} key={index}>
            <Cell isSlot={false} title="上报地址" val={item.address}></Cell>
            <Cell isSlot={false} isBorder={false} title="上报时间" val={item.address}></Cell>
          </View>
        ))}
      <Footer title="火灾信息"></Footer>
      {data.alarmRecord.length > 0 && (
        <View style={styles.fireInfo}>
          <Cell isSlot={false} title={data.alarmRecord[0].address}></Cell>
          <Cell isBorder={false} isSlot={false} title={data.alarmRecord[0].createDate}></Cell>
        </View>
      )}
      <Footer title="受困上报"></Footer>
      <View style={styles.trapped}>
        <Cell isSlot={true} isBorder={false} leftChild={<LeftChildView />} rightChild={<Stepper onGetNum={getStepperNum} number={data.trapNum} isInput={true}></Stepper>}></Cell>
      </View>
      <View style={{ marginBottom: 60 }}>
        {list.map((item, index) => (
          <View key={index}>
            <View style={styles.content}>
              <View style={styles.title}>
                <Text style={{ color: '#000', fontSize: 16 }}>{item.name}</Text>
              </View>
              <View style={styles.main}>{stateShow(item.name, item.type)}</View>
            </View>
            {item.type === 2 && (
              <TouchableOpacity
                style={styles.locationBtn}
                onPress={() => {
                  setShowModal(true);
                }}
              >
                <Text style={{ color: '#fff' }}>获取位置</Text>
              </TouchableOpacity>
            )}
          </View>
        ))}
      </View>
      <TouchableOpacity
        style={styles.uploadBtn}
        onPress={() => {
          TrappedSubmit();
        }}
      >
        <Text style={{ color: '#fff' }}>上报</Text>
      </TouchableOpacity>

      {/* 组件 */}
      <CascadingPicker show={data.pickerBuildShow} data={data.cascaderData} selectedIds={data.selectedBuildIds} onClose={() => (data.pickerBuildShow = false)} onConfirm={handleCascadingChange} title={'选择楼栋层门牌号'} />

      <Modal isOpen={showModal} onClose={() => setShowModal(false)}>
        <Modal.Content maxWidth="400px">
          <Modal.Header>提示</Modal.Header>
          <Modal.Body>选择地址是否清除已选择的楼栋层？</Modal.Body>
          <Modal.Footer>
            <Button.Group space={2}>
              <Button
                variant="ghost"
                colorScheme="blueGray"
                onPress={() => {
                  setShowModal(false);
                  getLocation('N');
                }}
              >
                不清除
              </Button>
              <Button
                colorScheme="red"
                onPress={() => {
                  setShowModal(false);
                  getLocation('Y');
                }}
              >
                清除
              </Button>
            </Button.Group>
          </Modal.Footer>
        </Modal.Content>
      </Modal>

      <Modal isOpen={showRecordModal} size={'md'}>
        <Modal.Content maxH="400">
          <Modal.Header style={{ alignItems: 'center' }}>选择一项报警</Modal.Header>
          <Modal.Body style={{ backgroundColor: '#f3f3f3' }}>
            <ScrollView>
              {data.alarmRecord.map((item, index) => (
                <TouchableOpacity
                  key={index}
                  style={[styles.recordView, data.selectId === item.alarmId && styles.selectColor]}
                  onPress={() => {
                    data.selectId = item.alarmId;
                  }}
                >
                  <View style={styles.recordChildView}>
                    <Text style={styles.recordText}>报警地址</Text>
                    <Text>{item.address}</Text>
                  </View>
                  <View style={{ borderBottomWidth: 1, borderColor: '#ddd', marginVertical: 4 }}></View>
                  <View style={styles.recordChildView}>
                    <Text style={styles.recordText}>报警时间</Text>
                    <Text>{item.createDate}</Text>
                  </View>
                </TouchableOpacity>
              ))}
            </ScrollView>
          </Modal.Body>
          <Modal.Footer style={{ justifyContent: 'center' }}>
            <TouchableOpacity
              style={{ width: '100%' }}
              onPress={() => {
                if (!data.selectId) {
                  toast.show('请选择一项报警', { placement: 'bottom' });
                  return false;
                }
                setShowRecordModal(false);
                data.alarmRecord = data.alarmRecord.filter((obj) => obj.alarmId === data.selectId);
                getHistoryTrappedRecord();
              }}
            >
              <Text style={[styles.textModalBtn]}>确 定</Text>
            </TouchableOpacity>
          </Modal.Footer>
        </Modal.Content>
      </Modal>
      <Modal isOpen={showTipsModal} size={'md'}>
        <Modal.Content maxH="400">
          <Modal.Header style={{ alignItems: 'center' }}>提示</Modal.Header>
          <Modal.Body style={{ backgroundColor: '#f3f3f3' }}>24小时内无火灾报警，无需上报</Modal.Body>
          <Modal.Footer style={{ justifyContent: 'flex-end' }}>
            <Button.Group space={2}>
              <Button
                variant="unstyled"
                colorScheme="coolGray"
                onPress={() => {
                  navigation.goBack();
                }}
              >
                取消上报
              </Button>
              <Button
                colorScheme="green"
                onPress={() => {
                  navigation.dispatch(StackActions.replace('fireDetection'));
                }}
              >
                新增消防报警
              </Button>
            </Button.Group>
          </Modal.Footer>
        </Modal.Content>
      </Modal>
    </ScrollView>
  );
};

const styles = StyleSheet.create({
  container: {
    padding: 16,
    height: 'auto',
  },
  fireInfo: {
    marginBottom: 20,
    backgroundColor: '#fff',
    borderRadius: 8,
  },
  trapped: {
    backgroundColor: '#fff',
    borderRadius: 8,
    marginBottom: 20,
  },
  uploadBtn: {
    backgroundColor: CommonStyle.mainColor,
    borderRadius: 8,
    height: 40,
    width: '90%',
    justifyContent: 'center',
    alignItems: 'center',
    position: 'absolute',
    bottom: 30,
    left: '5%',
  },
  title: {
    marginBottom: 10,
  },
  main: {
    width: '100%',
  },
  ldcView: {
    width: '100%',
    height: 36,
    alignItems: 'center',
    flexDirection: 'row',
    justifyContent: 'space-between',
    paddingHorizontal: 10,
    borderRadius: 8,
    borderWidth: 1,
    borderColor: '#ccc',
  },
  content: {
    width: '100%',
    minHeight: 10,
    marginBottom: 20,
    backgroundColor: '#fff',
    borderRadius: 8,
    padding: 10,
  },
  locationBtn: {
    marginBottom: 20,
    height: 40,
    backgroundColor: CommonStyle.mainColor,
    borderRadius: 8,
    justifyContent: 'center',
    alignItems: 'center',
  },
  textModalBtn: {
    width: '100%',
    fontWeight: 'bold',
    textAlign: 'center',
    color: CommonStyle.mainColor,
  },
  recordView: {
    backgroundColor: '#fff',
    borderRadius: 8,
    padding: 10,
    marginBottom: 10,
  },
  recordChildView: {
    height: 50,
    justifyContent: 'center',
  },
  recordText: {
    color: '#000',
    marginBottom: 4,
    fontWeight: 'bold',
  },
  selectColor: {
    borderWidth: 1,
    borderColor: CommonStyle.mainColor,
  },
});

export default TrappedReport;
